<?php
require_once("include/game_core.php");
require_once(USER_CONTROLLER_FILE);
require_once(DB_FILE);

if ( (! UserController::isLoggedIn()) ||
            (! UserController::isPlaying())  ) {
        header( 'Location: index.php' ) ;
    }

/////////////////////////
//      getGameId      //
/////////////////////////
    function getGameId($uid) {
        $query = "SELECT game_id , nick FROM users
                WHERE `id` = $uid 
                LIMIT 1";

        $db = new DBConnection();
        if ($db->executeQuery($query)) {
            $result = $db->getResult();
            if( ($result != null) && ($result->num_rows == 1) ) {
                $row = $result->fetch_assoc();
            }
        }
        if(isset($row)) {
                return $row;
        }
        return null;    
    }
/////////////////////////
//      pushMsg        //
/////////////////////////
    function pushMsg($uid, $new_msg, $nick, $game_id) {
        
        $query = "INSERT INTO chat (id,game_id,chat_str,nick)
            VALUES (?,?,?,?)";

        $db = new DBConnection();
        if( !$db->executeBindedQuery($query,"iiss",$uid, $game_id,$new_msg,$nick) ) {
            echo "ERRORrrrr";
        }
        

    }
/////////////////////////////////////////////////////
//                  script                         //
/////////////////////////////////////////////////////
    //get uid
    $uid = UserController::getUserId();
    if($uid == "") {
        echo "ERROR, cant get uid";
    }

    //get game_id
    $result = getGameId($uid);
    if($result == null) {
        return "ERROR in DB";
    }
    
    $game_id = $result['game_id'];
    $nick = $result['nick'];
    $new_msg = $_POST['chat'];
    
    //push to db 
    pushMsg($uid, $new_msg, $nick, $game_id);
    echo $nick. ": " .$new_msg;
    

?>
